package com.like.network;

import android.os.Handler;

import com.like.entity.EventWrapper;
import com.like.likeutils.network.GsonUtil;
import com.like.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class TokenInterceptor implements Interceptor {

    public static final String TAG_REFRESH_TOKEN = "refresh_token";

    private Handler mHandler;

    public TokenInterceptor() {
        mHandler = new Handler();
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        System.out.println("token intercept");
        Request request = chain.request();
        Response response = chain.proceed(request);
        String responseBody = response.newBuilder().build().body().string();
        Response newTokenResponse = response;
        try {
            JSONObject responseJson = new JSONObject(responseBody);
            if (responseJson.has("Result")) {
                int result = responseJson.getInt("Result");
                if (result == 4102) {
                    EventBus.getDefault().post(new EventWrapper(null, TAG_REFRESH_TOKEN));
                    String token = Constants.TOKEN;
                    while (Constants.TOKEN.equals(token)) {
                    }
                    responseJson.put("Secret", Constants.TOKEN);
                    ResponseBody body = ResponseBody.create(response.body().contentType(), responseJson.toString());
                    newTokenResponse = response.newBuilder().body(body).build();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return newTokenResponse;
    }

    private String stringifyRequestBody(Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

    public static Map<String, String> getQueryMap(String query) {
        String[] params = query.split("&");
        Map<String, String> map = new HashMap<>();
        for (String param : params) {
            String name = param.split("=")[0];
            String value = param.split("=")[1];
            map.put(name, value);
        }
        return map;
    }
}
